#pragma once
#include <iostream>
using namespace std;
#include <pthread.h>

namespace MyMutexModule
{
    class Mutex
    {
    public:
        Mutex(const Mutex &) = delete;
        const Mutex &operator=(const Mutex &) = delete;
        Mutex()
        {
            pthread_mutex_init(&_mutex, nullptr);
        }
        ~Mutex()
        {
            pthread_mutex_destroy(&_mutex);
        }

        void lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                cout << "lock fail" << endl;
                exit(1);
            }
        }

        void unlock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if (n != 0)
            {
                cout << "unlock fail" << endl;
                exit(1);
            }
        }

        pthread_mutex_t *getAddr()
        {
            return &_mutex;
        }

    private:
        pthread_mutex_t _mutex;
    };
    
    //采用RAII风格，进行锁的管理
    class LockGuard
    {
    public:
        LockGuard(Mutex &mutex)
            : _mutex(mutex)
        {
            _mutex.lock();
        }
        ~LockGuard()
        {
            _mutex.unlock();
        }

    private:
        Mutex &_mutex;
    };
}